package cn.shadow.message;

import cn.shadow.moulde.ISender;
import cn.shadow.moulde.ModuleHub;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import static cn.shadow.utils.BufferUtil.readVarInt32;

@Slf4j
public class ChannelSender implements ISender,MessageProcessor {
    private Channel channel;
    private ModuleHub moduleHub;

    public ChannelSender(Channel channel, ModuleHub moduleHub) {
        this.channel = channel;
        this.moduleHub = moduleHub;
    }

    @Override
    public void sendMessage(ByteBuf buffer) {
        logSendMessage(buffer);
        channel.writeAndFlush(buffer);
    }

    /**
     * 记录发送的消息
     */
    private void logSendMessage(ByteBuf buffer) {
        ByteBuf copy = buffer.copy(0, Math.min(12, buffer.readableBytes()));
        copy.skipBytes(2); //跳过两个字节
        int moduleId = readVarInt32(copy);
        int msgId = readVarInt32(copy);
        String s2cMsgName = moduleHub.getS2CMsgName(moduleId, msgId);
        if (s2cMsgName != null) {
            log.info("MsgName={},moduleId={},msgId={}", s2cMsgName, moduleId, msgId);
        } else {
            log.info("moduleId={},msgId={}", moduleId, msgId);
        }
    }


    @Override
    public void onMessage(ByteBuf byteBuf, int moduleID, int sequenceID) {

    }
}
